package com.android.physics;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.android.physics.Config.RoadblockConfig;
import com.android.physics.Config.StageConfig;

public class RoadblockGenerator
{
    private final Random mRandom;
    
    private List<Float> mRoadblockList = new ArrayList<Float>();
    private float mMaxHeight = 0;

    public RoadblockGenerator()
    {
        mRandom = new Random(System.currentTimeMillis());
        float a = 0.25f;
        final float maxSpeed = (float) Math.sqrt(Config.instance().getStage().getHeight()/4 * 2 * a);
        float halfA = a/2;
        float vs = 0;
        float S = 0;
        
        do
        {
            mRoadblockList.add(S);
            S += vs + halfA;
            vs += a;
        }
        while (vs < maxSpeed);
        mMaxHeight = 2 * S;
        do
        {
            mRoadblockList.add(S);
            vs -= a;
            S += vs + halfA;
        }
        while (vs > -maxSpeed);
        
        do
        {
            mRoadblockList.add(S);
            S += vs + halfA;
            vs += a;
        }
        while (vs < 0);
    }

    private int mTimeStamp = 0;

    public long getNextObjectTimeStamp()
    {
        return mTimeStamp;
    }

    public void resetTimeStamp()
    {
        mTimeStamp = 0;
    }

    public int getRandomIntInRange(int min, int max)
    {
        return mRandom.nextInt(max - min) + min;
    }

    public PhysicsObjectInStage<Roadblock> create()
    {
        PhysicsObjectInStage<Roadblock> roadblockInStage = new PhysicsObjectInStage<Roadblock>(new Roadblock());

        // 1. top, bottom
        boolean isTop = mRandom.nextBoolean();

        RoadblockConfig roadblockConfig = Config.instance().getRoadblock();
        StageConfig stageConfig = Config.instance().getStage();
        // 2. width & height
        int width = getRandomIntInRange(roadblockConfig.getMinWidth(), roadblockConfig.getMaxWidth());
        int height = 0;
        // 3. next time stamp
        int timeStamp = getRandomIntInRange(roadblockConfig.getMinTimeStampInterval(),
                roadblockConfig.getMaxTimeStampInterval());

        if (isTop)
        {
            height = mRoadblockList.get(mTimeStamp%mRoadblockList.size()).intValue();
        }
        else 
        {
            height = (int) (mMaxHeight - mRoadblockList.get(mTimeStamp%mRoadblockList.size()).intValue());
        }
        roadblockInStage.setSize(width, height);
        roadblockInStage.setPos(stageConfig.getWidth(), isTop ? 0 : stageConfig.getHeight() - height);
        roadblockInStage.setLife(mTimeStamp, mTimeStamp + roadblockConfig.getLifeCycle());
        roadblockInStage.setSpeedX(-stageConfig.getSpeed());
        mTimeStamp += timeStamp;
        return roadblockInStage;
    }
}
